package com.immoc.demo.config.dao;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @Author zzy
 * @Description TODO
 * @Date 2018/4/7 15:18
 * @Version 1.0
 **/
@Configuration
public class SqlSessionFactoryConfiguration {
    @Value("${mybatis_config_file}")
    private String mybatisConfigFilepath;
    @Value("${mapper_path}")
    private String mapperPath;
    @Autowired
    private DataSource dataSource;
    @Value("${entity_package}")
    private String entityPath;

    @Bean(name="sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //设置mybatis-config.xml路径
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilepath));
        //实例化mybatis解析文件类，此类用于解析配置mapper等配置文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //设置mapper文件的路径
        String packageSearchPath =  PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath;
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
        sqlSessionFactoryBean.setDataSource(dataSource);
        //设置映射对象的实体类路径
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPath);
        return sqlSessionFactoryBean;
    }
}
